package com.mzj.saas.commons.util;

import java.util.UUID;

import org.apache.commons.validator.routines.EmailValidator;

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;

public class ValidatorUtils
{
	public static boolean isUUID( String str )
	{
		if( str == null )
			return false ;
		int len = str.length() ;
		if( !(len == 32 || len == 36) )
			return false ;
		
		if( len == 32 )
		{
			StringBuilder strbuf = new StringBuilder() ;
			strbuf.append( str.substring(0, 8) ) ;
			strbuf.append( '-' ) ;
			strbuf.append( str.substring(8, 12) ) ;
			strbuf.append( '-' ) ;
			strbuf.append( str.substring(12, 16) ) ;
			strbuf.append( '-' ) ;
			strbuf.append( str.substring(16, 20) ) ;
			strbuf.append( '-' ) ;
			strbuf.append( str.substring(20, 32 ) ) ;
			str = strbuf.toString() ;
		}

		try
		{
			UUID.fromString( str ) ;
			return true ;
		}
		catch( IllegalArgumentException err )
		{
			return false ;
		}
	}
	
	private static final EmailValidator emailValidator = EmailValidator.getInstance(false) ;
	
	public static boolean isEmailAddress( String str )
	{
		if( str == null || str.length() < 5 )
			return false ;
		return emailValidator.isValid( str ) ;
	}

	private static final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance() ;
	
	public static boolean isPhoneNumber( String str )
	{
		if( str == null || str.length() < 6 )
			return false ;
		try
		{
			PhoneNumber phoneNumber = phoneNumberUtil.parse( str, "CN" ) ; 
			return phoneNumberUtil.isValidNumber( phoneNumber ) ;
		}
		catch( Throwable err )
		{
			return false ;
		}
	}
	
	private static final int[] IDCARD_WEIGHTS = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1} ;
	private static final char[] IDCARD_CHECKBITS = new char[]{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'} ;
	
	public static boolean isIdCard( String str )
	{
		if( str==null )
			return false ;
		int len = str.length() ;
		if( len==18 )
		{
			int year = ConvertUtils.str2int( str.substring(6,10) ) ;
			if( year<1890 )
				return false ;
			int month = ConvertUtils.str2int( str.substring(10,12) ) ;
			if( month>12||month<1 )
				return false ;
			int date = ConvertUtils.str2int( str.substring(12,14) ) ;
			if( date>31||date<1 )
				return false ;
			
			int sum = 0 ;
			for( int i=0; i<17; i++ )
				sum+= IDCARD_WEIGHTS[i]*Integer.parseInt(str.substring(i,i+1)) ;
			
			char checkBit = IDCARD_CHECKBITS[sum%11] ;
			return checkBit==Character.toUpperCase(str.charAt(17)) ;
		}
		else if( len==15 )
		{
			int month = ConvertUtils.str2int( str.substring(8,10) ) ;
			if( month>12||month<1 )
				return false ;
			int date = ConvertUtils.str2int( str.substring(10,12) ) ;
			if( date>31||date<1 )
				return false ;
			
			return true ;
		}
		else
			return false ;
	}
}
